<template>
  <FullPageModal
    v-model:visible="visible"
    hide-footer
    :body-style="{ padding: 0, overflow: 'hidden' }"
    :class="[isProjectSetting ? 'projectSetting-setPoint' : '']"
    :inset-cls="isProjectSetting ? '!inset-0' : void 0"
    :get-container="getContainer"
  >
    <div v-if="isEmpty" class="h-full flex flex-col items-center justify-center">
      <SlEmpty description="暂无属性数据，请先设置"></SlEmpty>
    </div>
    <div v-else class="h-full flex flex-col">
      <div class="flex flex-row items-center px-4.5 pt-4.5">
        <div class="flex-1">
          <a-input-search
            v-model:value="keyword"
            class="xl:!w-72"
            placeholder="搜索点位名称"
            size="small"
            @search="handleKeywordSearch"
          >
            <template #enterButton>
              <a-button>
                <template #icon><Icon type="icon-sousuo" /></template>
              </a-button>
            </template>
          </a-input-search>
        </div>
        <div>
          <a-button type="primary" danger :disabled="selectedRowKeys.length === 0" class="mr-2" @click="batchDel">
            删除点位
          </a-button>
          <a-button class="mr-2" @click="showCreateModal">新增点位</a-button>
          <a-button class="mr-2" @click="downloadTemplate">下载模板</a-button>
          <a-button class="mr-2">批量下载</a-button>
          <a-upload accept=".xls,.xlsx" :show-upload-list="false" :custom-request="customRequest">
            <a-button type="primary">导入Excel</a-button>
          </a-upload>
        </div>
      </div>
      <div class="flex-1 overflow-hidden">
        <SlTable
          :columns="columns"
          :loading="attrLoading || tableLoading || importing"
          :data-source="tableData"
          :pagination="pagination"
          :custom-row="customRow"
          row-key="gatewayDatapointId"
          :row-selection="{
            type: 'checkbox',
            selectedRowKeys,
            onChange,
          }"
          :search-model="searchModel"
          :ignore-keys="['gatewayId']"
        >
          <template #bodyCell="{ column, record }">
            <div v-if="column.dataIndex === 'oper'">
              <PermissionBtn :btn-props="{ type: 'link' }" class="mr-2" @click.stop="handleEditPoint(record)">
                编辑
              </PermissionBtn>
              <PermissionBtn :btn-props="{ type: 'link', danger: true }" @click.stop="handleDelPoint(record)">
                删除
              </PermissionBtn>
            </div>
            <EllipsisText v-else :max-len="20" :text="record[column.dataIndex as string]"></EllipsisText>
          </template>
        </SlTable>
      </div>
    </div>
    <CURDDialog
      :show-options="showOptions"
      id-key="gatewayDatapointId"
      :model="model"
      :model-form-setting="modelFormSetting"
      create-title="新增点位"
      update-title="编辑点位信息"
      delete-message="您确定删除该点位信息吗？删除后，将解除其下绑定的设备点位。"
      :curd="curd"
      :reload-table="reloadTable"
      :table-data="tableData"
      :drawer-container-selector="isProjectSetting ? '#project-detail-content' : void 0"
      @before-ok="beforeOk"
    />
  </FullPageModal>
</template>
<script setup lang="ts">
import type { TableColumnProps, UploadProps } from "ant-design-vue";
import { message } from "ant-design-vue";
import { ref, watch } from "vue";
import { Api, exportTemplate, importExcel } from "/@/api/aiot/gateway";
import { GatewayPointItem, GatewayTypeAttrItem } from "/@/api/aiot/gateway/models";
import { CURDAction, CURDModalEvent, FormItemData, ShowCURDModalOptions } from "/@/components/CURDDialog/models";
import { useCURD } from "/@/hooks/useCURD";
import { downloadFile } from "/@/utils/common";
import type { UploadRequestError } from "ant-design-vue/es/vc-upload/interface";
import InfoModal from "../../InfoModal";

const props = defineProps<{
  options?: { gatewayTypeId: string; gatewayId: string };
  isProjectSetting?: boolean;
  getContainer?: () => HTMLElement;
}>();
const isEmpty = ref(false);
const visible = ref(false);

/**
 * gatewayType attr
 */
const {
  tableData: attrData,
  tableLoading: attrLoading,
  reloadTable: reloadAttr,
} = useCURD<GatewayTypeAttrItem>({
  getPageUrl: Api.getGatewayTypeAttrs,
  loadOnMounted: false,
  pageSize: 999,
  loadFilter(data) {
    data.sort((a, b) => {
      return a.datapointAttrNumber - b.datapointAttrNumber;
    });
    return data;
  },
});
watch(
  () => props.options,
  async (v) => {
    if (v) {
      visible.value = true;
      keyword.value = "";
      await reloadAttr({ model: { gatewayTypeId: v.gatewayTypeId, searchText: "" } });
      isEmpty.value = attrData.value.length === 0;
      if (!isEmpty.value) {
        const newColumns: TableColumnProps<any>[] = attrData.value.map((el) => ({
          title: el.datapointAttrName,
          dataIndex: `attr${el.datapointAttrNumber}`,
          minWidth: 150,
        }));
        const newModel: any = {};
        const newModelFormSetting: FormItemData[] = [];
        attrData.value.forEach((attr, i) => {
          newModel[`attr${i}`] = "";
          newModelFormSetting.push({
            key: `attr${i}`,
            required: attr.requires,
            label: attr.datapointAttrName,
            max: 64,
          });
        });
        newModelFormSetting.push({
          subTitle: "点位扩展属性",
          beforeKey: "attr1",
          key: "_subTitle",
        });
        newModelFormSetting.push({
          subTitle: "点位默认属性",
          beforeKey: "attr0",
          key: "_subTitle",
        });
        modelFormSetting.value = newModelFormSetting;
        model.value = newModel;
        newColumns[0].fixed = "left";
        newColumns.push({
          title: "操作",
          dataIndex: "oper",
          fixed: "right",
        });
        columns.value = newColumns;
        reloadTable({
          model: {
            gatewayId: v.gatewayId,
            searchText: "",
          },
        });
      }
    } else {
      visible.value = false;
    }
  }
);
/**
 * gateway points
 */
const { tableData, tableLoading, reloadTable, curd, pagination, searchModel } = useCURD<GatewayPointItem>({
  getPageUrl: Api.gatewayDataPointsPage,
  createUrl: Api.addGatewayDatapoints,
  deleteUrl: Api.deleteGatewayPoints,
  updateUrl: Api.updateGatewayDatapoints,
  loadOnMounted: false,
  loadFilter(data) {
    data.forEach((el) => {
      let datapointAttrs: any;
      try {
        datapointAttrs = JSON.parse(el.datapointAttrs);
      } catch (err) {
        console.log("======>datapointAttrs parse error", err);
      }
      if (datapointAttrs) {
        const pointObj: any = {};
        for (let key in datapointAttrs) {
          const target = columns.value.find((el) => el.title === key);
          if (target) {
            pointObj[target.dataIndex as string] = datapointAttrs[key];
          }
        }
        Object.assign(el, pointObj);
      }
    });
    return data;
  },
});
const keyword = ref("");
function handleKeywordSearch() {
  reloadTable({
    model: {
      searchText: keyword.value,
    },
  });
}
const columns = ref<TableColumnProps<any>[]>([]);

/**
 * curd
 */
const model = ref<any>({});
const modelFormSetting = ref<FormItemData[]>([]);
const showOptions = ref<ShowCURDModalOptions>();
function showCreateModal() {
  showOptions.value = {
    action: CURDAction.CREATE,
  };
}
function beforeOk(e: CURDModalEvent) {
  if (!e.model) return;
  const obj: any = {};
  for (let key in e.model) {
    const target = modelFormSetting.value.find((el) => el.key === key);
    if (target) {
      obj[target.label as string] = e.model[key];
    }
  }
  e.model.gatewayId = props.options?.gatewayId;
  e.model.datapointAttrs = JSON.stringify(obj);
  //attr0是点位名称，需要做唯一校验
  e.model.gatewayDatapointName = e.model.attr0;
}
function handleEditPoint(record: GatewayPointItem) {
  showOptions.value = {
    action: CURDAction.UPDATE,
    record,
  };
}
function handleDelPoint(record: GatewayPointItem) {
  showOptions.value = {
    action: CURDAction.DELETE,
    record,
  };
}
/**
 * export import
 */
const importing = ref(false);
const customRequest: UploadProps["customRequest"] = async (options) => {
  if (!props.options) return;
  let formData = new FormData();
  formData.append("file", options.file);
  formData.append("gatewayId", props.options.gatewayId);
  importing.value = true;
  let req = await importExcel(formData);
  importing.value = false;
  if (req) {
    options.onSuccess &&
      options.onSuccess({
        status: "done",
      });
    message.success("操作成功");
    reloadTable();
  } else {
    let obj: UploadRequestError = {
      status: 500,
      name: "",
      message: "上传失败",
    };
    options.onError && options.onError(obj);
  }
};
async function downloadTemplate() {
  if (!props.options) return;
  const fileData = await exportTemplate(props.options.gatewayTypeId);
  if (fileData) {
    downloadFile(fileData, {
      name: "点位模板",
      contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
  }
}
/**
 * 批量删除
 */
const selectedRowKeys = ref<string[]>([]);
function onChange(keys) {
  selectedRowKeys.value = keys;
}
function customRow(record: GatewayPointItem) {
  return {
    onClick() {
      const index = selectedRowKeys.value.indexOf(record.gatewayDatapointId);
      if (index === -1) {
        selectedRowKeys.value.push(record.gatewayDatapointId);
      } else {
        selectedRowKeys.value.splice(index, 1);
      }
    },
  };
}
function batchDel() {
  InfoModal.confirm({
    content: `您确定删除所选${selectedRowKeys.value.length}个点位吗？`,
    async onOk() {
      if (curd.delete) {
        const re = await curd.delete(selectedRowKeys.value);
        if (re) {
          selectedRowKeys.value = [];
          message.success("操作成功");
          reloadTable();
        }
      }
    },
  });
}
</script>
<style lang="less">
.projectSetting-setPoint {
  .ant-modal-title {
    font-size: 18px;
  }
  .ant-modal-header {
    padding-left: 0;
  }
}
</style>
